/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosn.coffeemaker.project;

import com.nanosn.coffeemaker.Project;
import com.nanosn.util.FileUtility;
import fmpp.util.FileUtil;
import groovy.lang.GroovyClassLoader;
import java.io.File;
import java.io.IOException;
import org.codehaus.groovy.control.CompilationFailedException;

/**
 *
 * @author selkhateeb
 */
public class ProjectSettingsFactory {

    private static ProjectSettings instance;

    public static ProjectSettings getInstance()
            throws CompilationFailedException,
                   IOException,
                   InstantiationException,
                   IllegalAccessException {
//        return getInstance("Settings.java");
        return getInstance(Project.getDevelopmentDirectory());
    }

    public static ProjectSettings getInstance(String path)
            throws CompilationFailedException,
                   IOException,
                   InstantiationException,
                   IllegalAccessException {

        if (instance == null) {

            File settingsPath = new File(path);
            if (settingsPath.isDirectory()) {
                FileUtility.getFileListing(settingsPath);
                for (File file : FileUtility.getFileListing(settingsPath)) {
                    if (file.getAbsolutePath().endsWith("Settings.groovy")) {
                        path = file.getAbsolutePath();
                    }
                }
            }

            ClassLoader parent = ProjectSettingsFactory.class.getClassLoader();
            GroovyClassLoader loader = new GroovyClassLoader(parent);
            Class groovyClass = loader.parseClass(new File(path));

            instance = (ProjectSettings) groovyClass.newInstance();
        }
        return instance;
    }
}
